#!/bin/zsh
set -eu

APP_DIR="${0:A:h:h}"
PAYLOAD="$APP_DIR/Resources/RealtimeHub"
MOD_ID="RealtimeHub"

show_error() {
  if [[ "${ADOFAI_INSTALLER_TEST:-0}" == "1" ]]; then
    print -ru2 -- "$1"
  else
    /usr/bin/osascript -e "display alert \"ADOFAI Seethrough\" message \"$1\" as critical buttons {\"OK\"} default button \"OK\""
  fi
  exit 1
}

find_game() {
  setopt local_options null_glob
  local candidate
  local -a candidates
  candidates=(
    "$HOME/Downloads/ADOFAI/SteamLibrary/steamapps/common/A Dance of Fire and Ice"
    "$HOME/Library/Application Support/Steam/steamapps/common/A Dance of Fire and Ice"
  )
  for candidate in "${candidates[@]}" /Volumes/*/SteamLibrary/steamapps/common/'A Dance of Fire and Ice'; do
    if [[ -d "$candidate/ADanceOfFireAndIce.app" ]]; then
      print -r -- "$candidate"
      return 0
    fi
  done
  return 1
}

GAME_ROOT="${ADOFAI_GAME_ROOT:-$(find_game || true)}"
if [[ -z "$GAME_ROOT" ]]; then
  GAME_ROOT="$(/usr/bin/osascript -e 'POSIX path of (choose folder with prompt "Choose the A Dance of Fire and Ice game folder")' 2>/dev/null || true)"
  GAME_ROOT="${GAME_ROOT%/}"
fi

[[ -d "$GAME_ROOT/ADanceOfFireAndIce.app" ]] || show_error "That folder does not contain ADanceOfFireAndIce.app."
[[ -f "$PAYLOAD/RealtimeHub.dll" ]] || show_error "The installer payload is incomplete. Download the ZIP again."
UMM="$GAME_ROOT/ADanceOfFireAndIce.app/Contents/Resources/Data/Managed/UnityModManager/UnityModManager.dll"
[[ -f "$UMM" ]] || show_error "Unity Mod Manager is not installed in this ADOFAI copy."
if /usr/bin/pgrep -f '[A]DanceOfFireAndIce' >/dev/null 2>&1; then
  show_error "Quit A Dance of Fire and Ice before installing the mod."
fi

TARGET="$GAME_ROOT/Mods/$MOD_ID"
BACKUP_ROOT="$GAME_ROOT/ADOFAI Seethrough Backups"
BACKUP=""
/bin/mkdir -p "$GAME_ROOT/Mods"
if [[ -d "$TARGET" ]]; then
  /bin/mkdir -p "$BACKUP_ROOT"
  BACKUP="$BACKUP_ROOT/$MOD_ID.backup.$(/bin/date +%Y%m%d-%H%M%S)"
  SUFFIX=2
  while [[ -e "$BACKUP" ]]; do
    BACKUP="$BACKUP_ROOT/$MOD_ID.backup.$(/bin/date +%Y%m%d-%H%M%S)-$SUFFIX"
    (( SUFFIX += 1 ))
  done
  /bin/mv "$TARGET" "$BACKUP"
fi
if ! /bin/cp -R "$PAYLOAD" "$TARGET"; then
  /bin/rm -rf "$TARGET"
  if [[ -n "$BACKUP" && -d "$BACKUP" ]]; then
    /bin/mv "$BACKUP" "$TARGET"
  fi
  show_error "Installation failed. The previous mod was restored."
fi
/usr/bin/xattr -dr com.apple.quarantine "$TARGET" 2>/dev/null || true

if [[ "${ADOFAI_INSTALLER_TEST:-0}" == "1" ]]; then
  print -r -- "Installed ADOFAI Seethrough to $TARGET"
else
  /usr/bin/osascript -e 'display alert "ADOFAI Seethrough installed" message "Launch A Dance of Fire and Ice through Steam, then enter the Seethrough portal in the hub." buttons {"OK"} default button "OK"'
fi
